
import os
from listSplit import listSplit
from whiff.rdjson import jsonParse

class Sectionizer:
    """
    Look for using organization between files with naming convention:
       PrefixN_N_N_N.descriptiveName.whiff
    for example if prefix is "X" then
       X.intro.whiff is start document
       X10.tutorial.whiff is a top level entry
       X10_20.installing.whiff is a member of the tutorial
       X10_30.deleting.whiff is a later member of the tutorial.
    """
    def __init__(self, directory=".", prefix="W", suffix="whiff"):
        self.prefix = prefix
        self.suffix = suffix
        self.directory = directory
        self.filenameToLocator = {}
        self.locatorToFilename = {}
        filenames = os.listdir(directory)
        #pr "in directory", directory
        #pr "checking", filenames
        for filename in filenames:
            #pr "checking", filename
            test = fileNameTuple(filename, prefix, suffix)
            if test:
                #pr "found", test
                (locator, descriptive) = test
                self.filenameToLocator[filename] = locator
                self.locatorToFilename[locator] = filename
        fd = self.fileDictionaries = {}
        lf = self.locatorToFilename.items()
        for (locator, filename) in lf:
            fd[locator] = {"filename": filename, "children": []}
        # raises KeyError if any children are orphans
        for (locator, filename) in lf:
            if locator:
                parentLocator = locator[:-1]
                fd[parentLocator]["children"].append(locator)
    def getDictionary(self):
        result = {}
        locatorToDict = {}
        for (locator, fileDictionary) in self.fileDictionaries.items():
            outDict = fileDictionary.copy()
            #anchor = outDict["id"] = self.prefix+("_".join(locator))
            outDict["children"].sort()
            filename = outDict["filename"]
            anchor = outDict["id"] = ".".join(filename.split(".")[:-1])
            (title, summary) = getTitleAndSummary(self.directory, filename)
            outDict["title"] = title
            outDict["summary"] = summary
            outDict["body"] = """<a href="%s" title="%s">%s</a>""" % (anchor, title, title)
            result[anchor] = outDict
            locatorToDict[locator] = outDict
        # map in the parent ids and child ids
        for (locator, outDict) in locatorToDict.items():
            childLocators = outDict["children"]
            outDict["children"] = [ locatorToDict[childLocator]["id"] for childLocator in childLocators ]
            if locator:
                parentLocator = locator[:-1]
                parentDict = locatorToDict[parentLocator]
                outDict["parent"] = parentDict["id"]
        its = locatorToDict.items()
        its.sort()
        previousId = None
        for (locator, outDict) in its:
            outDict["previous"] = previousId
            previousId = outDict["id"]
        its.reverse()
        nextId = None
        for (locator, outDict) in its:
            outDict["next"] = nextId
            nextId = outDict["id"]
        return result
    def getJson(self):
        dictresult = self.getDictionary()
        return jsonParse.format(dictresult)
    def getPPDict(self):
        import pprint
        dictresult = self.getDictionary()
        return "Dictionary=" + pprint.pformat(dictresult)

def getTitleAndSummary(directory, filename):
    filepath = os.path.join(directory, filename)
    text = file(filepath).read()
    L = ["{{using", "title", "}}", "{{/using}}", "{{using", "summary", "}}", "{{/using}}"]
    sp = listSplit(text, L)
    title = sp[3]
    summary = sp[7]
    return (title, summary)
                
def isTuplePrefix(tuplePrefix, otherTuple):
    if tuplePrefix is None:
        return False
    ltp = len(tuplePrefix)
    if otherTuple is None or ltp>len(otherTuple):
        #pr (tuplePrefix, otherTuple), "not prefix, too long"
        return False
    truncTuple = otherTuple[:ltp]
    if truncTuple==tuplePrefix:
        return True
    return False

def tupleFileName(locator, prefix, suffix="whiff"):
    strs = [str(x) for x in locator]
    slocator = "_".join(strs)
    fs = [slocator, "DESCRIPTION", suffix]
    filename = prefix + ".".join(fs)
    return filename

def fileNameTuple(filename, prefix, suffix="whiff"):
    """
    for PrefixN_N_N_N.descriptiveName.whiff
    return ( (N,N,N,N), descriptiveName )
    or None on parse failure.
    """
    #pr "filenameTuple", (filename, prefix, suffix)
    if not filename.startswith(prefix):
        #pr "no prefix", (prefix, filename)
        return None
    filename = filename[ len(prefix): ]
    fs = filename.split(".")
    if len(fs)!=3:
        #pr "bad dot split", fs
        return None
    [locator, descriptiveName, suff] = fs
    if suff!=suffix:
        #pr "bad suffix", suff
        return None
    if not locator:
        locatorTuple = ()
    else:
        locatorTuple = tuple(locator.split("_"))
    return (locatorTuple, descriptiveName)

if __name__=="__main__":
    S = Sectionizer()
    print S.getPPDict()
